import { Router } from 'express'
import RoleDao from '../dao/RoleDao.js'
import Role from '../verify/Role.js'

let router = Router()

router.route('/api/role')
    .post(async (req, res) => {
        let role = Role.insertObj(req.body)
        if (!role) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await RoleDao.insert(role)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .delete(async (req, res) => {
        let role = Role.deleteObj(req.body)
        if (!role) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await RoleDao.delete(role)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .put(async (req, res) => {
        let role = Role.updateObj(req.body)
        if (!role) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await RoleDao.update(role)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

router
    .get('/api/role/:id', async (req, res) => {
        let result = await RoleDao.selectById(req.params.id)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/roleByPage/:pageIndex/:pageSize', async (req, res) => {
        let { pageIndex, pageSize } = req.params

        let result = await RoleDao.selectByLimit((pageIndex - 1) * pageSize, pageSize)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/roleTotal', async (req, res) => {
        let result = await RoleDao.selectCount()
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/roleByUserId/:user_id', async (req, res) => {
        let result = await RoleDao.selectByUserId(req.params.user_id)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

export default router